package FileIO;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FindFiles {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的根目录：");
        String srcPath = scanner.next();
        File srcFile = new File(srcPath);
        if (!srcFile.isDirectory()) {
            System.out.println("输入根目录不存在或不是目录，退出");
            return;
        }
        System.out.println("请输入要查找文件名中包含的字符：");
        String token = scanner.next();

        List<File> list = new ArrayList<>();
        scanSrcWithContent(srcFile, token, list);
        System.out.println("找到了符合条件的文件 "+list.size()+" 个");

        for (File file : list) {
            System.out.println(file.getCanonicalPath());
        }
    }

    private static void scanSrcWithContent(File srcFile, String token, List<File> list) {
        File[] files = srcFile.listFiles();
        if (files == null) return;
        for (File f : files) {
            if (f.isDirectory()){
             scanSrcWithContent(f, token, list);
            }else {
                if (isContentContains(f, token)) {
                    list.add(f.getAbsoluteFile());
                }
            }

    }
}

    private static boolean isContentContains(File file, String token) {
        StringBuilder sbr = new StringBuilder();
        try (InputStream is = new FileInputStream(file)){
            try (Scanner scanner = new Scanner(is, "UTF-8")){
                while (scanner.hasNextLine()) {
                    sbr.append(scanner.nextLine());
                    sbr.append("\r\n");
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sbr.indexOf(token) != -1;
    }
}
